package com.jamaskii.dictation;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.strictmode.WebViewMethodCalledOnWrongThreadViolation;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Layout;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jamaskii.ecdict.Word;
import com.jamaskii.ecdict.WordBook;
import com.jamaskii.ecdict.WordBookStream;
import com.jamaskii.utils.IOUtils;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.net.URI;
import java.util.ArrayList;

public class AcceptActivity extends BaseActivity {
    public static AcceptActivity instance;
    public WordBook book;
    public WordBookStream stream;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accept);
        instance=this;
        if(getIntent().getAction().equals(Intent.ACTION_SEND) || getIntent().getAction().equals(Intent.ACTION_VIEW)){
            try{
                init();
            }catch (Exception e){
                Toast.makeText(instance, e.toString(), Toast.LENGTH_LONG).show();
            }
        }else{
            finish();
        }
    }


    public void onBackClick(View view){
        instance=null;
        finish();
    }

    private void init(){
        try{
            Uri uri=getIntent().getData();
            String path=uri.getPath();
            File file=new File(path);
            if(!file.exists()){
                FileDescriptor fileDescriptor=getContentResolver().openFileDescriptor(uri,"r").getFileDescriptor();
                FileInputStream fileInputStream=new FileInputStream(fileDescriptor);
                path=getExternalCacheDir()+"/temp.wb";
                IOUtils.fileWriteString(path,IOUtils.readString(fileInputStream));
            }
            book=WordBook.loads(path);
            stream = new WordBookStream(getExternalFilesDir(null).getAbsolutePath() + "/books/");
            stream.loadWordBooks();
            if(book==null){
                Toast.makeText(instance, "文件格式不正确", Toast.LENGTH_SHORT).show();
            }else{
                showData();
            }
        }catch (Exception e){
            Toast.makeText(instance, e.toString(), Toast.LENGTH_LONG).show();
        }

    }

    private void showData(){
        TextView textView=findViewById(R.id.label_title);
        textView.setText(book.name);
        ArrayList<ItemData> items=new ArrayList<>();
        for (Word word:book.words
             ) {
            ItemData item=new ItemData(word,ItemType.SHOW_WORD);
            items.add(item);
        }
        ItemAdapter adapter=new ItemAdapter(this,R.layout.item_word_show,items);
        ListView listView=findViewById(R.id.listView_import);
        listView.setAdapter(adapter);
    }

    public void onImportClick(View view){
        //将单词本本地化
        book.times=0;
        book.last=" ";
        //如果存在同名单词本
        if(stream.checkExits(book.name)){
            Toast.makeText(AcceptActivity.this, "单词本名称重复", Toast.LENGTH_SHORT).show();

            final View layoutInput=getLayoutInflater().inflate(R.layout.dialog_input,null);
            final EditText textBoxNewName=layoutInput.findViewById(R.id.textbox_content_input_dialog);
            textBoxNewName.setText(book.name);

            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setView(layoutInput);
            builder.setTitle("新名称");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    try{
                        String name=textBoxNewName.getText().toString();
                        if(name.equals("")){
                            Toast.makeText(AcceptActivity.this, "名称不能为空", Toast.LENGTH_SHORT).show();
                        }else if(stream.checkExits(name)){
                            Toast.makeText(AcceptActivity.this, "单词本名称重复", Toast.LENGTH_SHORT).show();
                        }else{
                            book.name=name;
                            save();
                        }
                    }catch (Exception e)
                    {
                        Toast.makeText(AcceptActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            builder.setNegativeButton("取消",null);
            AlertDialog dialog=builder.create();
            dialog.show();
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(AcceptActivity.this.getResources().getColor(R.color.themeColor));
            dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(AcceptActivity.this.getResources().getColor(R.color.themeColor));
        }else{
            save();
        }

    }

    private void save(){
        book.save(stream.path);
        Toast.makeText(instance, "添加成功", Toast.LENGTH_SHORT).show();
        if(HomeActivity.instance!=null){
            HomeActivity.instance.loadBooks();
            HomeActivity.instance.linkData();
        }
        instance=null;
        finish();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        if(requestCode==2){
            init();
        }
    }


}